<?php

namespace App\Http\Controllers;

use App\Post;
use App\Comment;
use App\Zan;
use Illuminate\Http\Request;

class PostController extends Controller
{
    //文章列表页
    public function index()
    {

        $posts = Post::orderBy('created_at', 'desc')->withCount(["comments","zans"])->paginate(6);
        $posts->load('user');
        return view("post/index", compact('posts'));
    }

    //文章详情页
    public function show(Post $post)
    {
        //预加载
        $post->load('comments');

        return view("post/show", compact('post'));
    }

    //创建文章页面
    public function create()
    {
        return view("post/create");
    }

    //保存文章
    public function store()
    {
        //验证
        $this->validate(\request(), [
            'title' => 'required | string | max:100 | min:5',
            'content' => 'required | string | min:10'
        ]);

        //逻辑
        $user_id = \Auth::id();

        $params = array_merge(\request(['title', 'content']), compact('user_id'));

        $post =  Post::create($params);

        //渲染
        return redirect("/posts");

    }

    //编辑文章页面
    public function edit(Post $post)
    {
        return view("post/edit", compact('post'));
    }

    //修改文章
    public function update(Post $post)
    {
        //验证
        $this->validate(\request(), [
            'title' => 'required | string | max:100 | min:5',
            'content' => 'required | string | min:10'
        ]);

        //权限判断
        $this->authorize('update', $post);

        //逻辑
       $post->title = \request('title');
       $post->content = \request('content');
       $post->save();

        //渲染
        return redirect("/posts/{$post->id}");
    }

    //删除文章
    public function delete(Post $post)
    {
        //权限判断
        $this->authorize('delete', $post);

        $post->delete();

        return redirect("/posts");
    }

    //上传图片
    public function imageUpload(Request $request)
    {
        $path = $request->file('contentImage')->storePublicly(md5(time()));
//        return assert('http://localhost:8000/storage/'.$path);
        return response()->json('http://localhost:8000/storage/'.$path);
    }

    //评论
    public function comment(Post $post)
    {
        //验证
        $this->validate(\request(),[
            'content' => 'required | min:3',
        ]);

        //逻辑

        $comment = new Comment();
        $comment->user_id = \Auth::id();
        $comment->content = \request('content');
        $post->comments()->save($comment);

        //渲染
        return back();
    }

    //赞
    public function zan(Post $post)
    {
        $params = [
            'user_id' => \Auth::id(),
            'post_id' => $post->id
        ];

        Zan::firstOrCreate($params);
        return back();
    }

    //取消赞
    public function unzan(Post $post)
    {
        $post->zan(\Auth::id())->delete();
        return back();
    }
}
